// 聊天会话 Pinia Store，负责管理聊天相关的所有状态和操作
import { defineStore } from 'pinia'
import UNI_APP from '../.env'
import { MESSAGE_TYPE, MESSAGE_STATUS } from '@/common/enums.js'
import useUserStore from './userStore'

// 缓存会话数据，避免频繁操作原始数据
let cacheChats = []
export default defineStore('chatStore', {
  state: () => {
    return {
      chats: [], // 当前会话列表
      privateMsgMaxId: 0, // 私聊消息最大ID
      systemMsgMaxSeqNo: 0, // 系统消息最大序列号
      loadingPrivateMsg: false, // 私聊消息加载中
      loadingSystemMsg: false, // 系统消息加载中
    }
  },
  actions: {
    // 初始化会话列表
    initChats(chatsData) {
      cacheChats = []
      this.chats = []
      for (let chat of chatsData.chats) {
        chat.stored = false
        // 清理多余的消息，避免消息过多导致卡顿
        if (UNI_APP.MAX_MESSAGE_SIZE > 0 && chat.messages.length > UNI_APP.MAX_MESSAGE_SIZE) {
          chat.messages = chat.messages.slice(0, UNI_APP.MAX_MESSAGE_SIZE)
        }
        // 暂存至缓冲区
        cacheChats.push(JSON.parse(JSON.stringify(chat)))
        // 加载期间只显示前15个会话，加快初始化速度
        if (this.chats.length < 15) {
          this.chats.push(chat)
        }
      }
      this.privateMsgMaxId = chatsData.privateMsgMaxId || 0
      this.systemMsgMaxSeqNo = chatsData.systemMsgMaxSeqNo || 0
      // 防止图片消息一直处于加载中状态
      cacheChats.forEach((chat) => {
        chat.messages.forEach((msg) => {
          if (msg.loadStatus == 'loading') {
            msg.loadStatus = 'fail'
          }
        })
      })
    },
    // 打开一个会话，如果不存在则新建
    openChat(chatInfo) {
      let chats = this.curChats
      let chat = null
      for (let idx in chats) {
        if (chats[idx].type == chatInfo.type && chats[idx].targetId === chatInfo.targetId) {
          chat = chats[idx]
          // 移动到顶部
          this.moveTop(idx)
          break
        }
      }
      // 创建新会话
      if (chat == null) {
        chat = {
          targetId: chatInfo.targetId,
          type: chatInfo.type,
          showName: chatInfo.showName,
          headImage: chatInfo.headImage,
          lastContent: '',
          lastSendTime: new Date().getTime(),
          unreadCount: 0,
          messages: [],
          atMe: false,
          atAll: false,
          stored: false,
        }
        chats.unshift(chat)
        this.saveToStorage()
      }
    },
    // 激活会话，重置未读数
    activeChat(idx) {
      let chats = this.curChats
      console.log(this.curChats)
      if (idx >= 0) {
        chats.find((chat) => chat.targetId == idx).unreadCount = 0
      }
    },
    // 重置指定会话的未读数和@标记
    resetUnreadCount(chatInfo) {
      let chats = this.curChats
      for (let idx in chats) {
        if (chats[idx].type == chatInfo.type && chats[idx].targetId == chatInfo.targetId) {
          chats[idx].unreadCount = 0
          chats[idx].atMe = false
          chats[idx].atAll = false
          chats[idx].stored = false
          this.saveToStorage()
        }
      }
    },
    // 标记消息为已读
    readedMessage(pos) {
      let chat = this.findChatByFriend(pos.friendId)
      if (!chat) return
      chat.messages.forEach((m) => {
        if (m.id && m.selfSend && m.status < MESSAGE_STATUS.RECALL) {
          // pos.maxId为空表示整个会话已读
          if (!pos.maxId || m.id <= pos.maxId) {
            m.status = MESSAGE_STATUS.READED
            chat.stored = false
          }
        }
      })
      if (!chat.stored) {
        this.saveToStorage()
      }
    },
    // 移除会话
    removeChat(idx) {
      let chats = this.curChats
      chats[idx].delete = true
      chats[idx].stored = false
      this.saveToStorage()
    },
    // 移除私聊会话
    removePrivateChat(userId) {
      let chats = this.curChats
      for (let idx in chats) {
        if (chats[idx].type == 'PRIVATE' && chats[idx].targetId == userId) {
          this.removeChat(idx)
        }
      }
    },
    // 会话置顶
    moveTop(idx) {
      if (this.isLoading()) {
        return
      }
      let chats = this.curChats
      if (idx > 0) {
        let chat = chats[idx]
        chats.splice(idx, 1)
        chats.unshift(chat)
        chat.lastSendTime = new Date().getTime()
        chat.stored = false
        this.saveToStorage()
      }
    },
    // 插入消息到会话
    insertMessage(msgInfo, chatInfo) {
      // 获取对方id
      let type = chatInfo.type
      // 记录消息的最大id
      if (msgInfo.id && type == 'PRIVATE' && msgInfo.id > this.privateMsgMaxId) {
        this.privateMsgMaxId = msgInfo.id
      }
      if (msgInfo.seqNo && type == 'SYSTEM' && msgInfo.seqNo > this.systemMsgMaxSeqNo) {
        this.systemMsgMaxSeqNo = msgInfo.seqNo
      }
      // 如果是已存在消息，则覆盖旧的消息数据
      let chat = this.findChat(chatInfo)
      let message = this.findMessage(chat, msgInfo)
      if (message) {
        Object.assign(message, msgInfo)
        chat.stored = false
        this.saveToStorage()
        return
      }
      // 会话列表内容展示优化
      if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
        chat.lastContent = '[图片]'
      } else if (msgInfo.type == MESSAGE_TYPE.VIDEO) {
        chat.lastContent = '[视频]'
      } else if (msgInfo.type == MESSAGE_TYPE.FILE) {
        chat.lastContent = '[文件]'
      } else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
        chat.lastContent = '[语音]'
      } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VOICE) {
        chat.lastContent = '[语音通话]'
      } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VIDEO) {
        chat.lastContent = '[视频通话]'
      } else if (msgInfo.type == MESSAGE_TYPE.SYSTEM_MESSAGE) {
        chat.lastContent = msgInfo.title
      } else if (msgInfo.type == MESSAGE_TYPE.TEXT || msgInfo.type == MESSAGE_TYPE.RECALL || msgInfo.type == MESSAGE_TYPE.TIP_TEXT) {
        chat.lastContent = msgInfo.content
      }
      chat.lastSendTime = msgInfo.sendTime
      chat.sendNickName = msgInfo.sendNickName
      // 未读消息计数
      if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED && msgInfo.status != MESSAGE_STATUS.RECALL && msgInfo.type != MESSAGE_TYPE.TIP_TEXT) {
        chat.unreadCount++
      }
      // 超过10分钟插入时间提示
      if (!chat.lastTimeTip || chat.lastTimeTip < msgInfo.sendTime - 600 * 1000) {
        chat.messages.push({
          sendTime: msgInfo.sendTime,
          type: MESSAGE_TYPE.TIP_TIME,
        })
        chat.lastTimeTip = msgInfo.sendTime
      }
      // 根据id顺序插入，防止消息乱序
      let insertPos = chat.messages.length
      // 防止 图片、文件 在发送方 显示 在顶端  因为还没存库，id=0
      if (type != 'SYSTEM' && msgInfo.id && msgInfo.id > 0) {
        for (let idx in chat.messages) {
          if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
            insertPos = idx
            console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`)
            break
          }
        }
      }
      // 系统消息按序列号插入
      if (type == 'SYSTEM' && msgInfo.seqNo && msgInfo.seqNo > 0) {
        for (let idx in chat.messages) {
          if (chat.messages[idx].seqNo && msgInfo.seqNo < chat.messages[idx].seqNo) {
            insertPos = idx
            console.log(`消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`)
            break
          }
        }
      }
      if (insertPos == chat.messages.length) {
        // 直接追加
        chat.messages[insertPos] = msgInfo
      } else {
        // 插入到指定位置
        chat.messages.splice(insertPos, 0, msgInfo)
      }
      chat.stored = false
      this.saveToStorage()
    },
    // 更新消息内容
    updateMessage(msgInfo, chatInfo) {
      // 获取对方id
      let chat = this.findChat(chatInfo)
      let message = this.findMessage(chat, msgInfo)
      if (message) {
        // 属性拷贝
        Object.assign(message, msgInfo)
        chat.stored = false
        this.saveToStorage()
      }
    },
    // 删除消息
    deleteMessage(msgInfo, chatInfo) {
      // 获取对方id
      let chat = this.findChat(chatInfo)
      for (let idx in chat.messages) {
        // 已经发送成功的，根据id删除
        if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
          chat.messages.splice(idx, 1)
          break
        }
        // 正在发送中的消息可能没有id，只有临时id
        if (chat.messages[idx].tmpId && chat.messages[idx].tmpId == msgInfo.tmpId) {
          chat.messages.splice(idx, 1)
          break
        }
      }
      chat.stored = false
      this.saveToStorage()
    },
    // 撤回消息
    recallMessage(msgInfo, chatInfo) {
      let chat = this.findChat(chatInfo)
      if (!chat) return
      // 要撤回的消息id
      let id = msgInfo.content
      let name = msgInfo.selfSend ? '你' : chat.type == 'PRIVATE' ? '对方' : msgInfo.sendNickName
      for (let idx in chat.messages) {
        let m = chat.messages[idx]
        if (m.id && m.id == id) {
          // 改造成一条提示消息
          m.status = MESSAGE_STATUS.RECALL
          m.content = name + '撤回了一条消息'
          m.type = MESSAGE_TYPE.TIP_TEXT
          // 会话列表
          chat.lastContent = m.content
          chat.lastSendTime = msgInfo.sendTime
          chat.sendNickName = ''
          if (!msgInfo.selfSend && msgInfo.status != MESSAGE_STATUS.READED) {
            chat.unreadCount++
          }
        }
        // 被引用的消息也要撤回
        if (m.quoteMessage && m.quoteMessage.id == msgInfo.id) {
          m.quoteMessage.content = '引用内容已撤回'
          m.quoteMessage.status = MESSAGE_STATUS.RECALL
          m.quoteMessage.type = MESSAGE_TYPE.TIP_TEXT
        }
      }
      chat.stored = false
      this.saveToStorage()
    },
    // 更新会话信息（好友/用户）
    updateChatFromFriend(friend) {
      let chat = this.findChatByFriend(friend.id)
      if (chat && (chat.headImage != friend.headImage || chat.showName != friend.showNickName)) {
        // 更新会话中的群名和头像
        chat.headImage = friend.headImage
        chat.showName = friend.showNickName
        chat.stored = false
        this.saveToStorage()
      }
    },
    updateChatFromUser(user) {
      let chat = this.findChatByFriend(user.id)
      // 更新会话中的昵称和头像
      if (chat && (chat.headImage != user.headImageThumb || chat.showName != user.nickName)) {
        chat.headImage = user.headImageThumb
        chat.showName = user.nickName
        chat.stored = false
        this.saveToStorage()
      }
    },
    // 设置加载状态
    setLoadingPrivateMsg(loading) {
      this.loadingPrivateMsg = loading
      if (!this.isLoading()) {
        this.refreshChats()
      }
    },
    setLoadingSystemMsg(loading) {
      this.loadingSystemMsg = loading
      if (!this.isLoading()) {
        this.refreshChats()
      }
    },
    // 刷新会话列表（全部加载完毕后）
    refreshChats(state) {
      if (!cacheChats) {
        return
      }
      // 排序
      cacheChats.sort((chat1, chat2) => {
        return chat2.lastSendTime - chat1.lastSendTime
      })
      // 将消息一次性装载回来
      this.chats = cacheChats
      // 清空缓存,不再使用
      cacheChats = null
      this.saveToStorage()
    },
    // 保存到本地存储
    saveToStorage(state) {
      if (this.isLoading()) {
        return
      }
      const userStore = useUserStore()
      let userId = userStore.userInfo.id
      let key = 'chats-app-' + userId
      let chatKeys = []
      // 按会话为单位存储，只存储有改动的会话
      this.chats.forEach((chat) => {
        let chatKey = `${key}-${chat.type}-${chat.targetId}`
        if (!chat.stored) {
          if (chat.delete) {
            uni.removeStorageSync(chatKey)
          } else {
            let time = new Date().getTime()
            uni.setStorageSync(chatKey, chat)
          }
          chat.stored = true
        }
        if (!chat.delete) {
          chatKeys.push(chatKey)
        }
      })
      // 会话核心信息
      let chatsData = {
        privateMsgMaxId: this.privateMsgMaxId,
        systemMsgMaxSeqNo: this.systemMsgMaxSeqNo,
        chatKeys: chatKeys,
      }
      uni.setStorageSync(key, chatsData)
      // 清理已删除的会话
      this.chats = this.chats.filter((chat) => !chat.delete)
    },
    // 清空所有会话和状态
    clear(state) {
      cacheChats = []
      this.chats = []
      this.privateMsgMaxId = 0
      this.systemMsgMaxSeqNo = 0
      this.loadingPrivateMsg = false
      this.loadingSystemMsg = false
    },
    // 清理包含 undefined 的旧数据
    cleanUndefinedData() {
      try {
        // 获取所有存储键
        const keys = uni.getStorageInfoSync().keys

        // 查找包含 "undefined" 的键
        const undefinedKeys = keys.filter((key) => key.includes('undefined'))

        if (undefinedKeys.length > 0) {
          // 删除这些键
          undefinedKeys.forEach((key) => {
            uni.removeStorageSync(key)
          })
        } else {
        }
      } catch (error) {
        console.error('清理 undefined 数据时出错:', error)
      }
    },
    // 从本地存储加载会话
    loadChat(context) {
      return new Promise((resolve, reject) => {
        // 首先清理包含 undefined 的旧数据
        this.cleanUndefinedData()

        let userStore = useUserStore()
        let userId = userStore.userInfo.id

        // 如果 userStore 中的 userId 不存在或无效，尝试从本地存储获取
        if (!userId || userId === 'undefined' || userId === undefined) {
          userId = uni.getStorageSync('userId')
          if (!userId || userId === 'undefined' || userId === undefined) {
            console.warn('无法获取有效的用户ID，跳过加载聊天数据')
            resolve()
            return
          }
        }

        let chatsData = uni.getStorageSync('chats-app-' + userId)
        if (chatsData) {
          if (chatsData.chatKeys) {
            let time = new Date().getTime()
            chatsData.chats = []
            chatsData.chatKeys.forEach((key) => {
              let chat = uni.getStorageSync(key)
              if (chat) {
                chatsData.chats.push(chat)
              }
            })
          }
          this.initChats(chatsData)
        }
        resolve()
      })
    },
    // 拉取服务器会话消息
    fetchChats(silent = false) {
      return new Promise((resolve, reject) => {
        // 重置加载状态
        this.loadingPrivateMsg = true
        this.loadingSystemMsg = true

        // 获取App实例
        const app = getApp().$vm

        // 重新拉取消息
        Promise.all([app.pullPrivateOfflineMessage(this.privateMsgMaxId), app.pullSystemOfflineMessage(this.systemMsgMaxSeqNo)])
          .then(() => {
            // 设置加载完成
            this.loadingPrivateMsg = false
            this.loadingSystemMsg = false

            // 刷新显示，可选择静默更新
            if (!silent) {
              this.refreshChats()
            } else {
              // 静默更新，不触发大规模UI重绘
              this.silentRefreshChats()
            }

            resolve()
          })
          .catch((err) => {
            console.error('拉取消息失败', err)

            // 设置加载完成
            this.loadingPrivateMsg = false
            this.loadingSystemMsg = false

            // 尝试刷新现有数据
            try {
              if (!silent) {
                this.refreshChats()
              } else {
                this.silentRefreshChats()
              }
            } catch (e) {
              console.error('刷新聊天失败', e)
            }

            reject(err)
          })
      })
    },

    // 静默刷新会话数据，不触发大规模UI更新
    silentRefreshChats() {
      if (!cacheChats) {
        return
      }

      // 排序
      cacheChats.sort((chat1, chat2) => {
        return chat2.lastSendTime - chat1.lastSendTime
      })

      // 将消息一次性装载回来，但不触发大规模重绘
      for (let i = 0; i < cacheChats.length; i++) {
        if (i < this.chats.length) {
          // 更新现有聊天，而不是替换整个数组
          Object.assign(this.chats[i], cacheChats[i])
        } else {
          // 只添加新的聊天
          this.chats.push(cacheChats[i])
        }
      }

      // 清空缓存,不再使用
      cacheChats = null
      this.saveToStorage()
    },
  },
  getters: {
    // 判断是否有消息在加载中
    isLoading: (state) => () => {
      return state.loadingPrivateMsg || state.loadingSystemMsg
    },
    // 当前会话列表（优先缓存）
    curChats: (state) => {
      if (cacheChats && state.isLoading()) {
        return cacheChats
      }
      return state.chats
    },
    // 查找会话索引
    findChatIdx: (state) => (chat) => {
      let chats = state.curChats
      for (let idx in chats) {
        if (chats[idx].type == chat.type && chats[idx].targetId === chat.targetId) {
          chat = state.chats[idx]
          return idx
        }
      }
    },
    // 查找会话对象
    findChat: (state) => (chat) => {
      let chats = state.curChats
      let idx = state.findChatIdx(chat)
      return chats[idx]
    },
    // 通过好友ID查找私聊会话
    findChatByFriend: (state) => (fid) => {
      return state.curChats.find((chat) => chat.type == 'PRIVATE' && chat.targetId == fid)
    },
    // 查找消息（支持系统消息seqNo、普通消息id/tmpId）
    findMessage: (state) => (chat, msgInfo) => {
      if (!chat) {
        return null
      }
      if (chat.type == 'SYSTEM') {
        // 系统消息通过seqNo判断
        for (let idx in chat.messages) {
          if (msgInfo.seqNo && chat.messages[idx].seqNo == msgInfo.seqNo) {
            return chat.messages[idx]
          }
        }
      } else {
        for (let idx in chat.messages) {
          // 通过id判断
          if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
            return chat.messages[idx]
          }
          // 正在发送中的消息可能没有id,只有tmpId
          if (msgInfo.tmpId && chat.messages[idx].tmpId && msgInfo.tmpId == chat.messages[idx].tmpId) {
            return chat.messages[idx]
          }
        }
      }
    },
    // 通过 targetId 查找会话对象（通用方法）
    findChatByTargetId: (state) => (targetId) => {
      return state.curChats.find((chat) => chat.targetId == targetId)
    },
  },
})
